/* 
 * File:   Animation.cpp
 * Author: jcdenton
 * 
 * Created on July 2, 2010, 2:34 PM
 */

#include <iostream>
#include "Animation.hpp"

Animation::Animation(const std::string& path,
        int frameWidth,
        int frameHeight,
        bool isInfinite,
        int animationSleep) :
_frameIndex(0),
_frameWidth(frameWidth),
_frameHeight(frameHeight),
_animationSleep(animationSleep),
_isInfinite(isInfinite),
_currentFrame(new sf::Sprite()),
_framesVector(new std::vector<sf::Image*>())
{
    this->loadAnimation(this->loadBase(path));
}

Animation::~Animation()
{
}

sf::Image& Animation::loadBase(const std::string& p)
{
    std::string path = p;
    sf::Image* result = 0;
    if (path.empty())
        path = "img/error.png";
    result = new sf::Image();
    if (!result->LoadFromFile(path))
        throw ("Animation::loadbase : impossible to load image " + path);
    return (*result);
}

void Animation::loadAnimation(sf::Image& base)
{
    this->_frameMax = base.GetWidth() / this->_frameWidth;
    for (int i = 0; i < this->_frameMax; i++)
    {

        this->_framesVector->push_back(new sf::Image(
                static_cast<unsigned int> (this->_frameWidth),
                static_cast<unsigned int> (this->_frameHeight)));
                (*this->_framesVector)[i]->Copy(base, 0, 0,
                sf::IntRect(this->_frameWidth * i, 0,
                this->_frameWidth * (i + 1),
                this->_frameHeight));
    }
    this->_frameIndex = 0;
    this->_currentFrame->SetImage((*(*this->_framesVector)[0]));
    delete &base;
}

const sf::Sprite& Animation::getFrame()
{
    if (this->_frameMax > 1)
        this->nextFrame();
    this->_currentFrame->SetPosition(100, 100);
    return (*this->_currentFrame);
}

void Animation::nextFrame()
{
    static int timer = 0;

    if (timer == this->_animationSleep)
    {
        if (!this->_isInfinite && this->_frameIndex == this->_frameMax - 1)
            return ;
        this->_currentFrame->SetImage((*(*this->_framesVector)[this->_frameIndex]));
        if (this->_frameIndex == this->_frameMax - 1)
                this->_frameIndex = 0;
        else
            this->_frameIndex++;
            timer = 0;
        }
    else
        timer++;
}